/*
 * Copyright (C) 2012 Damien Girard <dgirard@nativesoft.fr>
 * Copyright (C) 2012 Sebastien Baudrand <sebbaudrand@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fr.umlv.qroxy.communication.transfer;

import fr.umlv.qroxy.cache.CacheWriter;
import fr.umlv.qroxy.communication.Connection;
import fr.umlv.qroxy.rules.Rule;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Logger;

/**
 * Fixed transfer operation.
 *
 * To use when the Content-length is known.
 *
 * @author Damien Girard <dgirard@nativesoft.fr>
 * @author Sebastien Baudrand <sebbaudrand@gmail.com>
 */
public class FixedTransfer implements Transfer {

    private final long size;
    private int headerHttpSize;
    private long totalRead = 0;
    private long totalWrite = 0;
    private CacheWriter cacheWriter;

    /**
     * Fixed transfer.
     *
     * @param size Size, amount of data to read and write. Do not forget to
     * include the size of the HTTP header. Example: httpHeaderSize + Content
     * Length
     */
    public FixedTransfer(long size) {
        this.size = size;
        this.cacheWriter = null;
        this.headerHttpSize = 0;
    }

    /**
     * Fixed transfer.
     *
     * @param size Size, amount of data to read and write. Do not forget to
     * include the size of the HTTP header. Example: httpHeaderSize + Content
     * Length
     * @param 
     */
    public FixedTransfer(long size, int headerHttpSize, CacheWriter cacheWriter) {
        this.size = size;
        this.cacheWriter = cacheWriter;
        this.headerHttpSize = headerHttpSize;
    }

    @Override
    public TransferResult read(SocketChannel channel, ByteBuffer buffer, boolean useOnlyBuffer) throws IOException {
        if (!useOnlyBuffer) {
            int nbRead = channel.read(buffer);
            if (nbRead < 0) {
                return new TransferResult(nbRead, false);
            }

            totalRead += nbRead;

            return new TransferResult(nbRead, true);
        } else {
            return new TransferResult(0, true);
        }
    }

    @Override
    public TransferResult write(SocketChannel channel, ByteBuffer buffer, int limit) throws IOException {
        // Sanity check.
        if (totalWrite > size) {
            throw new RuntimeException("Transfer: All data were already write. YOU MUST NOT CALL THIS METHOD IF EVERYTHING IS WRITTEN.");
        }

        // Storing buffer informations.
        int bufferLimit = buffer.limit();
        int bufferPosition = buffer.position();

        // Rewinding the buffer and setting the limits to the
        // amount of data that I have to write.
        buffer.position(0);

        if (totalWrite + bufferPosition > size) {
            buffer.limit((int) (size - totalWrite)); // I have to write only a part of the buffer.
        } else {
            buffer.limit(bufferPosition); // I have to write the entire buffer.
        }

        // Handling the limit (for QoS).
        if (limit > 0 && buffer.limit() > limit) {
            buffer.limit(limit);
        }

        // Writing.
        int nbWrite = channel.write(buffer);
        if (nbWrite < 0) {
            // Restauring buffer state.
            buffer.limit(bufferLimit);
            buffer.position(bufferPosition);

            return new TransferResult(nbWrite, false);
        }

        // Writing data wrote from the network to the cache.
        if (cacheWriter != null) {
            if (nbWrite > headerHttpSize) {
                // Storing position and limit.
                int storedLimit = buffer.limit();
                int storedPosition = buffer.position();

                //Connection.debugPrintBuffer(buffer);
                buffer.limit(buffer.position());
                buffer.position(headerHttpSize);

                try {
                    cacheWriter.write(buffer);
                } catch (IOException e) {
                    Logger.getLogger(CacheWriter.class.getName()).info("Error while writing data to cache file" + e);
                    cacheWriter.close(true);
                    cacheWriter = null;
                }

                buffer.limit(storedLimit);
                buffer.position(storedPosition);

                // Header http skipped, now writing all data to the cache.
                headerHttpSize = 0;
            }
        }

        // Data wrote.
        totalWrite += nbWrite;

        // Compacting the buffer and reseting everything.
        buffer.limit(bufferPosition);
        buffer.compact();

        buffer.limit(bufferLimit);
        buffer.position(bufferPosition - nbWrite);

        return new TransferResult(nbWrite, (totalWrite >= size), (buffer.position() != 0));
    }
}
